import type { Settings as LayoutSettings } from '@ant-design/pro-layout';
import { history } from 'umi';
import type { } from 'antd';
import type { SizeType } from 'antd/es/config-provider/SizeContext';
import getApiData from '@/services/cpasRequest';
import getIcon from '@/utils/icon';
import { msgInfo } from '@/utils/msg';

// 登录路由，这个比较特殊
export const loginPath = '/user/login';

/**
 * 子系统的定义
 */
export type SysName = 'audit' | 'main' | 'cloudConvert' | undefined;
/**
 * 全局状态 类型定义，放在这里是因为 它与 app.tsx有关，目前与app.tsx有关的都先放这里一部分，减少app.tsx中的代码量。在初始化时使用
 */
export type InitState =
  | {
    settings?: Partial<LayoutSettings> & {
      frameUrl?: string;
      componentSize?: SizeType;
      customerlevel_isABC?: boolean;
      cpasTableZeroReplace: string;
      negationRow: string[]
    } & any;
    curUser?: any; //
    curPassword?: string; // 这个目前还不知道在那种场景下有用
    sysName?: SysName;
    curPart?: any;
    menuJson?: any[];
  }
  | undefined;
/**
 * 一般是指路由变化时触发（可将登录，认证等逻辑放这）
 * @param init
 */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
export async function onLayoutPC(init: InitState) {
  const { location } = history;
  // if (!init?.curUser) {
  //   const token = getToken();
  //   if (token) {
  //     const res = await getUserInfo(); // 获取当前用户信息
  //     if (res.ok) {
  //       setInit({
  //         ...init,
  //         curUser: res.data
  //       })
  //       if (location.pathname === loginPath) {
  //         history.push('/');
  //       }
  //     }
  //   } else if (location.pathname !== loginPath) {
  //     history.push(loginPath);
  //   }
  // }

  // 如果没有登录，重定向到 login
  if (!init?.curUser && location.pathname !== loginPath) {
    history.push(loginPath);
  }
}

/**
 * 扩展区域 目前只有开发模式下显示
 * @returns
 */
export function layoutLinks(): React.ReactNode[] {
  if (process.env.NODE_ENV === 'development') {
    return [<></>];
  }
  return [<></>];
}

/**
 * 根据路由获取系统名称
 * @param pathname
 * @returns
 */
export function getSysName(pathname: string): SysName {
  return pathname.startsWith('/audit/') ? 'audit' : 'main';
}

/**
 * 这里可以根据不同子系统初始化不同 layout
 * @param initialState
 * @returns
 */
export function getRunTimeLayoutConfig(initialState: InitState & any) {
  // let tempCollapsed: any = null;
  // const onCollapse = (collapsed: any) => {
  //   tempCollapsed = collapsed ? layoutLinksFalse() : layoutLinks();
  //   console.log(tempCollapsed);
  //   return tempCollapsed;
  // };

  const { menuJson } = initialState;

  function parseMenu() {
    const parseMenuJson = (menuData: any): void => {
      menuData.forEach((menu: any) => {
        if (menu.icon) {
          menu.icon = getIcon(menu.icon);
        } else {
          menu.icon = <div style={{
            width: "10px", height: "10px",
          }} />;
        }
        menu.key = menu.path;
        if (menu.children) {
          parseMenuJson(menu.children);
        }
      });
    };
    parseMenuJson(menuJson);
    return menuJson;
  }

  function getRoutesItemByPath(mjson: any, path: any) {
    let matchItem = null;
    function findNodeByKeyIteration(matchStr: any, data: string | any[]) {
      for (let i = 0; i < data.length; i++) {
        const dataItem = data[i];
        if (dataItem.children) {
          findNodeByKeyIteration(matchStr, dataItem.children);
        }
        if (dataItem.path === path) {
          matchItem = dataItem;
          break;
        }
      }
    }
    findNodeByKeyIteration(path, mjson);
    return matchItem;
  }

  return {
    // contentStyle: { background: '#eee' },
    disableContentMargin: true, // 内容展示区域的 Margin
    // logo 单击事件
    onMenuHeaderClick: () => {
      if (initialState?.sysName === 'audit') {
        history.push('/audit/home');
      } else {
        history.push('/home');
      }
    },
    // onCollapse,
    onPageChange: () => {
      onLayoutPC(initialState);
    },
    links: false,
    waterMarkProps: {
      content: initialState?.curUser?.usercode,
    },
    menuProps: {
      items: parseMenu(),
      onClick: (menu: any) => {
        const path = menu.item.props.path;
        const matchRoutes: any = getRoutesItemByPath(menuJson, path);
        const getzcbfInfo: any = window.sessionStorage.getItem("electronParams") || {};
        const zcbfInfo = JSON.parse(getzcbfInfo);
        const paramsData = {
          appName: matchRoutes.label, appType: '路由菜单',
          params: {
            part: zcbfInfo?.params ?? {}
          }
        }
        window.main.behavior("312", { ...paramsData, appName: matchRoutes.label });
        if (matchRoutes.type === "exe") {
          msgInfo(`正在打开 ${matchRoutes.label},请稍候...`);
          // UserCode={1} UserPwd={c4ca4238a0b923820dcc509a6f75849b} ProjectCode={202202-AUD-2020-001} ZcbfID={202202-AUD-2020-001}
          if (window.electronComponents) {
            const sessionParams = JSON.parse(window.sessionStorage.electronParams);
            const { sjxmbh, ZcbfID } = sessionParams.params

            window.location.href = `cpas://OpenLocalFile/?fileName={UFCPAS4_PATH}/UFCPAS4.exe&params=UserCode={UserCode} UserPwd={UserPwd} ProjectCode=${sjxmbh} ZcbfID=${ZcbfID}&workDir={UFCPAS4_PATH}/SysBPL/`;
          } else {
            console.error("window[\"electronComponents\"] false")
          }
        } else {
          history.push(menu.key);
        }
      },
    },
  };
}
